//
//  YYEComposePictureView.swift
//  weibo14
//
//  Created by mac on 16/3/13.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class YYEComposePictureView: UICollectionView {

    
    // 给外界准备一个回调的闭包 执行选择器用
    var selectedPictureClosure: (()->())?
    
    var images:[UIImage] = [UIImage]() {
        didSet{
            reloadData()
        }
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame ,collectionViewLayout : layout)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI(){
        
        self.dataSource = self
        
        self.delegate = self
     
        self.registerClass(YYEPictureViewCell.self, forCellWithReuseIdentifier: "YYEPictureViewCell")
     
        self.backgroundColor = UIColor.clearColor()
    }
    
    func addImage(image:UIImage) {
        images.append(image)
    }
    
    override func layoutSubviews() {
        
        let itemMargin: CGFloat = 5
        let itemWH = CGFloat(Int((self.frame.width - 2 * itemMargin) / 3))
        
        // 能够获取到当前控件的最新宽高
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        // 设置条目之前的间距
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
        
        super.layoutSubviews()
    }
}

extension YYEComposePictureView: UICollectionViewDataSource,UICollectionViewDelegate {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
        if images.count == 0 || images.count == 9 {
        
            return images.count
        }
        
        return images.count + 1
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("YYEPictureViewCell", forIndexPath: indexPath) as! YYEPictureViewCell
        
        cell.deleteButtonClickClosure = { [weak self] (cell: YYEPictureViewCell)->()  in
        
            let idx = self!.indexPathForCell(cell)
        
            self!.images.removeAtIndex((idx?.item)!)
            
            self!.reloadData()
        }
        
        if images.count == indexPath.item {
            cell.picture = nil
        } else {
            cell.picture = images[indexPath.item]
        }
        
        return cell
    }
    
    // 取消选中效果  代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        
        // 判断是加号按钮
        let cell =  collectionView.cellForItemAtIndexPath(indexPath) as! YYEPictureViewCell
        
        if cell.picture == nil {
            // print("!!!!!!!!!!!!")
            
            selectedPictureClosure?()
        }
    }
    
}

class YYEPictureViewCell: UICollectionViewCell {

    var deleteButtonClickClosure:((cell: YYEPictureViewCell)->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        addSubview(vc)
        addSubview(deleteButton)
        
        deleteButton.snp_makeConstraints(closure: { (make) -> Void in
            
            make.top.trailing.equalTo(contentView)
        })
        
        
        vc.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
    
    }
    
    var picture:UIImage? {
    
        didSet {
            if picture == nil {
                deleteButton.hidden = true
                vc.image = UIImage(named: "compose_pic_add")
                vc.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
            }else  {
                deleteButton.hidden = false
                vc.image = picture
                vc.highlightedImage = picture
            }
        }
    }

    let vc:UIImageView = {
        let vc = UIImageView()
        
        vc.contentMode = .ScaleAspectFill
        vc.clipsToBounds = true
        return vc
    }()
    
    // 删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "delebuttonClick", forControlEvents: UIControlEvents.TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        return button
    }()

    @objc private func delebuttonClick(){
        deleteButtonClickClosure?(cell: self)
    }
}

